package com.yc.io.netty.demo2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MyServer {
	
	public void bind(int port) {
		EventLoopGroup brossGroup = new NioEventLoopGroup();
		EventLoopGroup wokerGroup = new NioEventLoopGroup();
		
		try {
			//服务端工具类
			ServerBootstrap b = new ServerBootstrap();
			b.group(brossGroup, wokerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());
			ChannelFuture f = b.bind(port).sync();//绑定端口
			System.out.println(Thread.currentThread().getName() + ", 服务器开始监听端口，等待客户端连接...");
			f.channel().closeFuture().sync();//阻塞
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			//关闭资源
			brossGroup.shutdownGracefully();
			wokerGroup.shutdownGracefully();
		}
		
		
		
	}
	
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ch.pipeline().addLast(new MyServerHandler());
		}
		
	} 

	public static void main(String[] args) {
		int port = 12333;
		new MyServer().bind(port);

	}

}
